import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart';
import 'l10n/app_localizations.dart';

class SettingsPage extends StatefulWidget {
  const SettingsPage({Key? key}) : super(key: key);

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  String _selectedLanguage = 'zh'; // 默认中文
  final String _appVersion = '1.0.0';

  // 添加主题模式设置
  bool _isDarkMode = true;

  @override
  void initState() {
    super.initState();
    _loadPreferences();
  }

  // 加载所有偏好设置
  Future<void> _loadPreferences() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _selectedLanguage = prefs.getString('language') ?? 'zh';
      _isDarkMode = prefs.getBool('dark_mode') ?? true;
    });
  }

  // 保存语言偏好设置
  Future<void> _saveLanguagePreference(String languageCode) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('language', languageCode);
    setState(() {
      _selectedLanguage = languageCode;
    });

    // 显示需要重启的提示
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('语言设置已更改，重启应用后生效'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  // 保存主题模式设置
  Future<void> _saveThemeMode(bool isDark) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('dark_mode', isDark);
    setState(() {
      _isDarkMode = isDark;
    });
  }

  // 拨打电话
  Future<void> _makePhoneCall(String phoneNumber) async {
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    try {
      await launchUrl(launchUri);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法拨打电话: $e')),
        );
      }
    }
  }

  // 复制文本到剪贴板
  Future<void> _copyToClipboard(String text, String message) async {
    await Clipboard.setData(ClipboardData(text: text));
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message)),
      );
    }
  }

  // 打开网站
  Future<void> _openWebsite(String url) async {
    if (!url.startsWith('http')) {
      url = 'https://$url';
    }

    try {
      await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法打开网站: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);

    // 定义主题颜色
    final backgroundColor = _isDarkMode ? Colors.black : Colors.grey[100];
    final cardColor = _isDarkMode ? Colors.grey[900] : Colors.white;
    final textColor = _isDarkMode ? Colors.white : Colors.black87;
    final secondaryTextColor = _isDarkMode ? Colors.white70 : Colors.black54;
    final accentColor = Colors.amber[400];

    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.settings),
        backgroundColor: backgroundColor,
        foregroundColor: textColor,
        elevation: 0,
      ),
      body: Container(
        color: backgroundColor,
        child: ListView(
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
          children: [
            // 基本设置分组
            _buildSectionHeader('基本设置', textColor),

            // 卡片式设置组
            Card(
              color: cardColor,
              elevation: 2,
              margin: const EdgeInsets.symmetric(vertical: 8),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                children: [
                  // 语言设置
                  ListTile(
                    leading: Icon(Icons.language, color: accentColor),
                    title: Text(
                      localizations.language,
                      style: TextStyle(color: textColor),
                    ),
                    trailing: DropdownButton<String>(
                      value: _selectedLanguage,
                      dropdownColor: cardColor,
                      underline: Container(),
                      icon: Icon(Icons.arrow_drop_down, color: textColor),
                      items: <String>['zh', 'en']
                          .map<DropdownMenuItem<String>>((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(
                            value == 'zh' ? '中文' : 'English',
                            style: TextStyle(color: textColor),
                          ),
                        );
                      }).toList(),
                      onChanged: (String? newValue) {
                        if (newValue != null) {
                          _saveLanguagePreference(newValue);
                        }
                      },
                    ),
                  ),

                  // 分隔线
                  Divider(
                      height: 1, color: secondaryTextColor.withOpacity(0.2)),

                  // 深色模式设置
                  SwitchListTile(
                    secondary: Icon(
                      _isDarkMode ? Icons.dark_mode : Icons.light_mode,
                      color: accentColor,
                    ),
                    title: Text(
                      '深色模式',
                      style: TextStyle(color: textColor),
                    ),
                    value: _isDarkMode,
                    activeColor: accentColor,
                    onChanged: (bool value) {
                      _saveThemeMode(value);
                    },
                  ),
                ],
              ),
            ),

            const SizedBox(height: 24),

            // 关于分组
            _buildSectionHeader('关于', textColor),

            // 卡片式版权信息
            Card(
              color: cardColor,
              elevation: 2,
              margin: const EdgeInsets.symmetric(vertical: 8),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        CircleAvatar(
                          backgroundColor: accentColor,
                          foregroundColor: Colors.black,
                          child: const Text('坚',
                              style: TextStyle(fontWeight: FontWeight.bold)),
                        ),
                        const SizedBox(width: 12),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '坚果补光灯',
                              style: TextStyle(
                                color: textColor,
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            Text(
                              '版本 $_appVersion',
                              style: TextStyle(
                                  color: secondaryTextColor, fontSize: 14),
                            ),
                          ],
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    _buildInfoRow(
                      Icons.person,
                      '作者：坚果派',
                      accentColor,
                      secondaryTextColor,
                      onTap: () => _copyToClipboard('坚果派', '作者名称已复制到剪贴板'),
                    ),
                    _buildInfoRow(
                      Icons.chat,
                      '公众号：nutpi',
                      accentColor,
                      secondaryTextColor,
                      onTap: () => _copyToClipboard('nutpi', '公众号已复制到剪贴板'),
                    ),
                    _buildInfoRow(
                      Icons.phone,
                      '电话：17752170152',
                      accentColor,
                      Colors.blue,
                      isLink: true,
                      onTap: () => _makePhoneCall('17752170152'),
                    ),
                    _buildInfoRow(
                      Icons.language,
                      '官网：www.nutpi.net',
                      accentColor,
                      Colors.blue,
                      isLink: true,
                      onTap: () => _openWebsite('www.nutpi.net'),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 应用描述
            Card(
              color: cardColor,
              elevation: 2,
              margin: const EdgeInsets.symmetric(vertical: 8),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Text(
                  '坚果补光灯是一款专为自拍和视频录制设计的补光工具，提供多种预设颜色和自定义选项，帮助您在任何光线条件下拍摄出色彩丰富的照片和视频。',
                  style: TextStyle(color: secondaryTextColor, height: 1.5),
                ),
              ),
            ),

            const SizedBox(height: 24),

            // 版权声明
            Center(
              child: Text(
                '© 2023 坚果派. 保留所有权利.',
                style: TextStyle(color: secondaryTextColor, fontSize: 12),
              ),
            ),

            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  // 构建分组标题
  Widget _buildSectionHeader(String title, Color textColor) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Text(
        title,
        style: TextStyle(
          color: textColor,
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  // 构建信息行
  Widget _buildInfoRow(
    IconData icon,
    String text,
    Color? iconColor,
    Color textColor, {
    bool isLink = false,
    required VoidCallback onTap,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
              Icon(icon, color: iconColor, size: 20),
              const SizedBox(width: 12),
              Expanded(
                child: Text(
                  text,
                  style: TextStyle(
                    color: textColor,
                    fontSize: 15,
                    decoration: isLink ? TextDecoration.underline : null,
                  ),
                ),
              ),
              if (isLink) Icon(Icons.open_in_new, color: textColor, size: 16),
            ],
          ),
        ),
      ),
    );
  }
}
